using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace AIFSContentManagementSystem.DomainObjects
{
    public sealed class Parser : IParser
    {
        private const string REG_PATTERN = @"__\w+__";

        public Parser()
        {            
        }

        public void Parse(IParsable Parsable)
        {
            if (Parsable == null)
                throw new ArgumentException("Article can not be null");

            if (Parsable.Fragments == null || Parsable.Fragments.Count == 0)
                throw new ArgumentException("Must contain at least one article before parsing");

            if (Parsable.PlaceHolders == null)
                Parsable.PlaceHolders = new List<PlaceHolder>();

            //Keep track of all placeholders
            StringCollection placeHolders = new StringCollection();

            Regex regEx = new Regex(REG_PATTERN, RegexOptions.IgnoreCase | RegexOptions.Multiline);

            foreach (Fragment fragment in Parsable.Fragments)
            {
                //Search in the header
                Match match = regEx.Match(fragment.HeaderText);
                while (match.Success)
                {
                    if (!placeHolders.Contains(match.Value))
                        placeHolders.Add(match.Value);

                    match = match.NextMatch();
                }

                //Search in the body
                match = regEx.Match(fragment.HtmlBody);
                while (match.Success)
                {
                    if (!placeHolders.Contains(match.Value))
                        placeHolders.Add(match.Value);

                    match = match.NextMatch();
                }
            }

            //Fill the IParsable's place holder
            foreach (string val in placeHolders)
            {
                PlaceHolder placeHolder = new PlaceHolder();
                placeHolder.Name = val;

                Parsable.PlaceHolders.Add(placeHolder);
            }
        }
    }
}